package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import cloudContact.Common;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

/**
 * Servlet implementation class UserLocation
 */
@WebServlet("/UserLocation")
public class UserLocation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserLocation() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("Start UserLocation...");

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				out.println("Error: User is not authorized.");
				return;
			}

			HttpSession session = request.getSession();

			User user = null;
			try {
				user = UserDAO.getInstance().lookup(
						session.getAttribute("userId").toString());
			} catch (RollbackException e) {
				e.printStackTrace();
			} catch (MyDAOException e) {
				e.printStackTrace();
			}

			if (user == null) {
				out.println("Error: User not found.");
				return;
			}
			
			user.setLastSeenLatitude(Float.valueOf(request.getParameter("latitude")));
			user.setLastSeenLongitude(Float.valueOf(request.getParameter("longtitude")));
			
			UserDAO.getInstance().update(user);
			
		} catch (NumberFormatException e) {
			out.print("Invalid location");
		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
			System.out.println("Finish UserLocation.");
		}
	}

}
